
package org.hydrakyoufeng.stuplatform.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.utility.RandomString;
import org.hydrakyoufeng.stuplatform.dto.UserDTO;
import org.hydrakyoufeng.stuplatform.dto.UserListDTO;
import org.hydrakyoufeng.stuplatform.mapper.UserMapper;
import org.hydrakyoufeng.stuplatform.service.UserService;
import org.hydrakyoufeng.stuplatform.utils.ResultEntity;
import org.hydrakyoufeng.stuplatform.vo.UserListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    @Qualifier("adminIdTheadLocal")
    private ThreadLocal<Integer> adminIdTheadLocal;

    /**
     * 导出excel功能，获取不分页的用户列表
     * @param userListDTO
     * @return
     */
    @Override
    public List<UserListVO> getExcel(UserListDTO userListDTO) {
        return userMapper.queryList(userListDTO);
    }

    @Override
    public ResultEntity queryList(UserListDTO userListDTO)  {
        log.info("userListDTO = " + userListDTO);
        // 开启分页
        PageHelper.startPage(userListDTO.getCurrentPage(),
                userListDTO.getPageSize(),
                "u.update_time desc");
        PageInfo pageInfo = new PageInfo(userMapper.queryList(userListDTO));
        return ResultEntity.success("查询成功",pageInfo);
    }

    @Override
    public ResultEntity insert(UserDTO userDTO) throws Exception {
        userDTO.setCreator_by(adminIdTheadLocal.get());
        userDTO.setUpdate_by(adminIdTheadLocal.get());
        // 生成6为随机数作为盐
        String salt = RandomString.make(6);
        userDTO.setSalt(salt);
        // 假设新创建用户的默认状态为0或其它初始值
        userDTO.setStatus("0");
        int result = userMapper.insert(userDTO);
        if (result > 0) {
            return ResultEntity.success("添加成功");
        } else {
            return ResultEntity.error("添加失败");
        }
    }

    @Override
    public ResultEntity update(UserDTO userDTO) throws Exception {
        userDTO.setUpdate_by(adminIdTheadLocal.get());
        int result = userMapper.update(userDTO);
        if (result > 0) {
            return ResultEntity.success("修改成功");
        } else {
            return ResultEntity.error("修改失败");
        }
    }

    @Override
    public ResultEntity<Object> delete(Integer id) {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(id);
        userDTO.setUpdate_by(adminIdTheadLocal.get());
        int result = userMapper.delete(userDTO);
        if (result > 0) {
            return ResultEntity.success("删除成功");
        } else {
            return ResultEntity.error("删除失败");
        }
    }
}